/*
 *英才会硕信息科技有限公司拥有本软件的版权，拥有本软件版权2025   并保留所有权利。
 *Copyright 2021,YCHS Information&Science Technology Co.,Ltd,
 *All rights reserved.
 */
package com.ychs.lawyerback01.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ychs.lawyerback01.common.Constant;
import com.ychs.lawyerback01.common.ResultCode;
import com.ychs.lawyerback01.exception.BussinessException;
import com.ychs.lawyerback01.util.JwtUtils;
import com.ychs.lawyerback01.vo.LoginVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.concurrent.TimeUnit;

/**
 *过滤器  springmvc拦截器，aop通知切到controller层，controller异常处理
 * @author xuehongjin
 * @version 1.0
 * @date 2025/8/14
 */
@Component
@Slf4j
public class Logininterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //跨域请求
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        //获得token的值
        String auth = request.getHeader("Authorization");
        if (StrUtil.isEmpty(auth)||!auth.startsWith("Auth")){
            log.info("token不存在");
            throw new BussinessException(ResultCode.TOKEN_NOTFPUND);
        }
        String token =auth.substring(5);
        //2.解析token，获取token登录用户

        String id = jwtUtils.extractId(token);
        if (StrUtil.isEmpty(id)){
            //token不合法
            throw new BussinessException(ResultCode.TOKEN_NOTVALID);
        }
        //3.通过id从redis获取当前访问的用户是否登
        String userVoStr=(String)redisTemplate.opsForValue().get(Constant.TOKEN_PREFIX + id);
        LoginVo loginVo = JSONUtil.toBean(userVoStr, LoginVo.class);
        if(StrUtil.isBlank(userVoStr)){
            throw new BussinessException(ResultCode.TOKEN_EXPIRE);
        }
        //4.判断token是否需要续期
       long expire = redisTemplate.getExpire(Constant.TOKEN_PREFIX+id, TimeUnit.SECONDS);
        if(expire<Constant.TOKEN_REMAINING){
            //续期
            redisTemplate.expire(Constant.TOKEN_PREFIX,Constant.TOKEN_TIME,TimeUnit.SECONDS);
        }
        //5.把当前登录的用户放到request域中，后续使用
        request.setAttribute("loginUserVo",loginVo);

        return true;
    }
}
